const path = require("path");
const { lstatSync, readdirSync } = require('fs')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const fse = require("fs-extra");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin  = require("extract-text-webpack-plugin");
const StringReplacePlugin = require("string-replace-webpack-plugin");
const rimraf = require('rimraf');
const argv = require('yargs').argv
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const config = require("./config.dev");

let utils = {};
utils.assetsPath = function (_path) {
    var assetsSubDirectory = "";
    return path.posix.join(assetsSubDirectory, _path)
}
utils.isDirectory = source => lstatSync(source).isDirectory()
utils.getSubDictories = source => {
    return readdirSync(source).map(name => path.join(source, name)).filter(utils.isDirectory)
}

module.exports = function(root) {

    const pages = utils.getSubDictories(path.resolve(root, "src/pages"));
    let entry = {};
    entry["app"] = path.resolve(root, "src/app.js");

    for (let pagename in pages) {
        let paths = pages[pagename].split(path.sep);
        entry[paths[paths.length - 1]] = path.resolve(pages[pagename]);
    }

    var output = path.resolve(root, 'web');

    rimraf.sync(path.join(output, "dist"));
    return  {
        entry: entry,
        output: {
            path: output,
            filename: utils.assetsPath('dist/pages/[name]/index.[chunkhash:8].js'),
            chunkFilename: utils.assetsPath(`dist/pages/[name]/[name].[chunkhash:8].js`)
        },
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: ExtractTextPlugin.extract({
                        fallback: "style-loader",
                        use: "css-loader"
                    })
                },
            ]
        },
        plugins: [
            new HtmlWebpackPlugin({
                template: path.resolve(root, "src/app.html"),
                filename: `app.html`,
                chunksSortMode: function (a, b) {  //alphabetical order
                   var aname = a.names[0].split("-")[1];
                   var bname = b.names[0].split("-")[1];              
                   if (aname > bname) {
                     return 1;
                   }
                   if (aname < bname) {
                     return -1;
                   }
                   return 0;
               }
            }),
            new ExtractTextPlugin("dist/css/[name]-[chunkhash:8].css"),
            new CopyWebpackPlugin(config.webpackconfig.plugins["CopyWebpackPlugin"][0])
        ]
    }
};